<template>
  <div class="model-body">
    <div class="title">数据总体情况表</div>
    <dv-decoration-5 style="width:100%;height:30px;color:" :color="['#ffffff', '#1C5BEC']" :dur="5" />
    <div class="table">
      <div class="left">
        <div class="time-btn" v-for="item in dataList" :key="item.value" :class="time === item.value ? 'active' : ''"
          @click="timeCheckedTwo(item.value)">
          {{ item.label }}
        </div>
      </div>
      <div class="right">
        <vxe-table border show-footer ref="tableRef" height="auto" align="center" :loading="loading" :print-config="{}"
          :column-config="{ resizable: true }" :span-method="spanMethods" :merge-footer-items="mergeFooterItems"
          :footer-method="footerMethod" :data="tableData">
          <vxe-column field="SampleNo" title="样品编号"></vxe-column>
          <vxe-colgroup title="实验项目">
            <vxe-column field="ItemName" title=""></vxe-column>
            <vxe-column field="ResultName" title=""></vxe-column>
          </vxe-colgroup>
          <vxe-colgroup title="数据">
            <vxe-column field="TotalCount" title="个数"></vxe-column>
          </vxe-colgroup>
          <vxe-colgroup title="满意结果">
            <vxe-column field="SatisfiedCount" title="个数"></vxe-column>
            <vxe-column field="SatisfiedPercent" title="百分比"></vxe-column>
          </vxe-colgroup>
          <vxe-colgroup title="可疑结果">
            <vxe-column field="SuspiciousCount" title="个数"></vxe-column>
            <vxe-column field="SuspiciousPercent" title="百分比"></vxe-column>
          </vxe-colgroup>
          <vxe-colgroup title="不满意结果">
            <vxe-column field="UnSatisfiedCount" title="个数"></vxe-column>
            <vxe-column field="UnSatisfiedPercent" title="百分比"></vxe-column>
          </vxe-colgroup>
        </vxe-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, reactive, watch, onMounted, onUnmounted, ref, computed, defineEmits } from "vue";
const props = defineProps({
  datas: {
    type: Object,
    required: true
  },
  dataList: {
    type: Array,
    required: true
  },
  time: {
    type: String,
    required: true
  }
})
const list = ref([])

watch(() => props.time, (newValue) => {
  console.log(newValue);
  initData()
});
const loading = ref(false)
const tableData = ref([])
const mergeFooterItems = ref([])
const tableRef = ref()
const toolbarRef = ref()
const timeInfo = reactive({
  setInterval: 0,
  dateDay: "",
  dateYear: "",
  dateWeek: "",
})
const summarize = (items, prop) => {
  const sum = items.reduce((total, item) => total + item[prop], 0);
  const count = items.length;
  const average = count > 0 ? (sum / count * 100).toFixed(2) : 0;
  return { sum, average, count };
};
const footerMethod = ({ columns, data }) => {
  return [
    columns.map((column, index) => {
      let result;
      if (index === 0) {
        result = '/'
      }
      else if (index === 1) {
        result = '总计'
      } else {
        const list = data.map(item => ({
          TotalCount: item.TotalCount,
          SatisfiedCount: item.SatisfiedCount,
          SatisfiedPercent: parseFloat(item.SatisfiedPercent.replace('%', '')) / 100,
          SuspiciousCount: item.SuspiciousCount,
          SuspiciousPercent: parseFloat(item.SuspiciousPercent.replace('%', '')) / 100,
          UnSatisfiedCount: item.UnSatisfiedCount,
          UnSatisfiedPercent: parseFloat(item.UnSatisfiedPercent.replace('%', '')) / 100
        }));
        const { sum, average } = summarize(list, column.field);
        if (column.field === 'TotalCount') {
          result = sum
        } else if (column.field === 'SatisfiedCount') {
          result = sum
        } else if (column.field === 'SatisfiedPercent') {
          result = average + "%"
        } else if (column.field === 'SuspiciousCount') {
          result = sum
        } else if (column.field === 'SuspiciousPercent') {
          result = average + "%"
        } else if (column.field === 'UnSatisfiedCount') {
          result = sum
        } else if (column.field === 'UnSatisfiedPercent') {
          result = average + "%"
        }
      }
      return result
    })
  ]
}
const initData = () => {
  list.value = props.datas.MData;
  loading.value = true
  loading.value = false
  let array = []
  for (let index = 0; index < list.value.length; index++) {
    const element = list.value[index];
    const itemList = element.OverallDataDetail.map(e => {
      e.SampleNo = element.SampleNo
      return e
    })
    array = array.concat(itemList)
  }

  tableData.value = array
}
/**
 * 二维数组合并单元格（仅针对数组对象本身）
 * @param data 接口返回的数组对象
 * @param field 指定合并选项为数组对象的某个属性值
 * @param colArr 需要合并列的下标
 * @returns mergeCells单元格合并规则
 */
function spanMethods({ row, $rowIndex, column, data }) {
  let fields = ["SampleNo", "ItemName"]
  let cellValue = row[column.property]
  if (cellValue && fields.includes(column.property)) {
    let prevRow = data[$rowIndex - 1]
    let nextRow = data[$rowIndex + 1]
    if (prevRow && prevRow[column.property] === cellValue) {
      return { rowspan: 0, colspan: 0 }
    } else {
      let countRowspan = 1
      while (nextRow && nextRow[column.property] === cellValue) {
        nextRow = data[++countRowspan + $rowIndex]
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 }
      }
    }
  }
}
// 根据行数据计算表尾合并规则
mergeFooterItems.value = [
  { row: 0, col: 1, rowspan: 1, colspan: 2 },
]
const emits = defineEmits(['timeCheckedTwo'])// 定义一个或多个自定义事件
const timeCheckedTwo = (time) => {
  emits('timeCheckedTwo', time)
}
// 生命周期
onMounted(() => {
  initData()
  // 将表格和工具栏进行关联
  const $table = tableRef.value
  const $toolbar = toolbarRef.value
  if ($table && $toolbar) {
    $table.connect($toolbar)
  }
})
onUnmounted(() => {
  clearInterval(timeInfo.setInterval)
})
</script>

<style lang="scss" scoped>
.model-body {
  width: 100%;

  .title {
    width: 100%;
    padding: 10px;
    text-align: center;
    font-size: 26px;
    color: #ffffff;
    // margin-bottom: 10px;
  }

  .table {
    height: 70vh;
    display: flex;

    .left {
      width: 100px;
      padding-right: 20px;

      .time-btn {
        text-align: center;
        padding: 10px;
        width: 80px;
        background-color: #0873AA;
        color: #ffffff;
        margin-bottom: 10px;

        &:hover {
          cursor: pointer;
          background-color: #32A4F1
        }

        &.active {
          background-color: #32A4F1
        }

      }
    }

    .right {
      height: 100%;
      width: 800px;
    }
  }
}

::v-deep(.vxe-header--column) {
  background: #0873AA;
  color: #ffffff;
}

::v-deep(.vxe-body--column) {
  background: #32A4F1;
  color: #ffffff;
}

::v-deep(.vxe-footer--column) {
  background: #0873AA;
  color: #ffffff;
}
</style>
